<script setup>
import {Panel, useVueFlow} from '@vue-flow/core'
import {editProcessData, syncKnowledgeConDetail} from "@/renderer/api/dict";
import {message} from "ant-design-vue";
import {CloudSyncOutlined, ImportOutlined, SaveOutlined} from '@ant-design/icons-vue';

import {h} from 'vue';
import useDragAndDrop from "@/renderer/views/vue-flow/useDnD";

const emit = defineEmits(['updateNodes','addMutil']);
const { toMath } = useDragAndDrop()
const props = defineProps({
  queId: {
    type: String,
    required: true,
  },
  nodes:{
    type: Array,
    required: true,
  },
  knowledgeConclusions:{
    type: Array,
    required: true,
  }
})
const flowKey = 'vue-flow--save-restore'

const { nodes, addNodes, dimensions, toObject, fromObject } = useVueFlow()



let  open = ref(false)
let  modalVisible = ref(false)
let  all = ref(false)


let  syncData = reactive({
  knowledgeConclusionId:''

})

let  openSync =()=>{
  open.value = true
}

let  openSingleSync =(data)=>{
  all.value = false
  modalVisible.value = true
  for (const dataKey in data) {
    syncData[dataKey] = data[dataKey]
  }
}


let conclusionNodes = computed(()=>{
  return  nodes.value.filter(item=>{
    return item.data.type === 'conclusion-result'
  }).map(item=>{
    // 使用正则表达式匹配 ### 后的标题和内容
    const match = item.data.nodeName.match(/###\s*(.*?)\n([\s\S]*)/);
    let  title = '';
    let content = ''
    if (match) {
      title = match[1].trim(); // 标题：二项式的充要条件 :
      content = match[2].trim(); // 换行后的所有内容
    }
    return {
      knowNodeId:item.id,
      knowledgeConclusionTagLabel:title,
      knowledgeConclusionTag:item.data.knowledgeConclusionTag,
      id:item.data.conclusionId,
      nodeBindConclusionId:item.data.nodeBindConclusionId,
      techniqueDetail:content,
      avatar:item.data.icon,
      knowledgeConclusionId:item.data.knowledgeConclusionId,
      knowledgeConclusionLabel:item.data.knowledgeConclusionLabel,
      knowId:props.queId
    }
  })
})
let  handleOk = ()=>{
  let  newList = []
  if (all.value ===false){
    newList = [{...syncData}];
    if (syncData?.knowledgeConclusionTagLabel.trim()===''){
      message.error("请输入主结论标题!")
      throw new Error(`请输入主结论标题!`)
    }

  }else{
    newList.push(...conclusionNodes.value.map(item=>({
      ...item,
      knowledgeConclusionId:syncData.knowledgeConclusionId
    })))

    newList.forEach((item,index)=>{
      console.log(item, 'item')

      if (item?.knowledgeConclusionTagLabel.trim()===''){
        message.error(`第${index+1}个结论请输入主结论标题!`)
        throw new Error(`第${index+1}个结论请输入主结论标题!`)
      }
    })
  }
  syncKnowledgeConDetail({newList}).then(res=>{
    if (res.code === 200){
      message.success("同步成功!")
      emit('updateNodes', res.data);
    }
  }).finally(()=>{
    modalVisible.value = false
  })

  console.log(newList, 'newList')
  syncData.knowledgeConclusionId = ''
}

let  handleCancel = ()=>{
  modalVisible.value = false
  syncData.knowledgeConclusionId = ''
}


let  closeSync =()=>{
  open.value = false
}
let  unifiedSync =()=>{
  all.value = true
  modalVisible.value = true
}


let  handleAddMutil =()=>{
  emit('addMutil');
}


function onSave() {
  let {nodes, edges} = toObject();
  let nodeDataList = nodes.map(item => {
    return {...item.position, id: item.id, queId: props.queId, nodeName: item.data.nodeName,nodeType:item.data.type,                 nodeContent: item.data.nodeContent,
      nodeTitle:item.data.nodeTitle,nodeDataSubList:item.data.nodeDataSubList}
  })
  let edgeDataList = edges.map(item => {
    return {
      ...item, queId: props.queId, name: item.data.name,
      sourceNodeId: item.source,
      targetNodeId: item.target
    }
  })
  const data = {nodeDataList, edgeDataList, queId: props.queId}
  editProcessData(data).then(res => {
    message.success("保存成功!")
  })
}

function onRestore() {
  const flow = JSON.parse(localStorage.getItem(flowKey))

  if (flow) {
    fromObject(flow)
  }
}

function onAdd() {
  const id = nodes.value.length + 1

  const newNode = {
    id: `random_node-${id}`,
    label: `Node ${id}`,
    position: { x: Math.random() * dimensions.value.width, y: Math.random() * dimensions.value.height },
  }

  addNodes([newNode])
}
</script>

<template>
  <Panel position="top-right">
    <div class="buttons">
      <a-tooltip>
        <template #title>
          <span>同步</span>
        </template>
        <a-button type="text" :icon="h(CloudSyncOutlined)"  @click="openSync">
        </a-button>
      </a-tooltip>
      <a-divider type="vertical" style="width: 2px;height:100%; background-color: #7cb305" />
      <a-tooltip>
        <template #title>
          <span>保存</span>
        </template>
        <a-button type="text" :icon="h(SaveOutlined)"  @click="onSave">
        </a-button>
      </a-tooltip>
      <a-divider type="vertical"  />
      <a-tooltip>
        <template #title>
          <span>批量新增</span>
        </template>
        <a-button type="text" :icon="h(ImportOutlined)" @click="handleAddMutil">
        </a-button>
      </a-tooltip>

      <!--      <a-divider type="vertical" style="width: 2px;height:100%; background-color: #7cb305" />-->
      <!--      <a-button  @click="handleAddMutil" :icon="h(SaveOutlined)" type="primary">-->
      <!--        解析MD-->
      <!--      </a-button>-->
    </div>

  </Panel>
  <a-modal   v-model:open="modalVisible"  @cancel="handleCancel" title="同步框" @ok="handleOk">
    <h3>
      绑定主结论
    </h3>
    <a-select v-model:value="syncData.knowledgeConclusionId" style="width: 100%">
      <a-select-option v-for="(item,index) in knowledgeConclusions" :key="index" :value="item.id">
        <p v-html="toMath(item.title)"></p>
      </a-select-option>
    </a-select>
  </a-modal>
  <a-drawer
      v-model:open="open"
      class="custom-class"
      :closable="false"
      :footer-style="{ textAlign: 'right' }"
      title="同步知识点结论"
      placement="right"
      width="50%"
  >
    <template #footer>
      <a-button style="margin-right: 8px" @click="closeSync">取消</a-button>
      <a-button type="primary" @click="unifiedSync">统一同步</a-button>
    </template>
    <a-list
        class="demo-loadmore-list"
        item-layout="horizontal"
        :data-source="conclusionNodes"
    >
      <template #renderItem="{ item }">
        <a-list-item>
          <template #actions>
            <a-button ghost  :icon="h(CloudSyncOutlined)" type="primary" @click="openSingleSync(item)"></a-button>
          </template>
          <a-list-item-meta>
            <template #title>
              <h3 v-html="toMath(item.knowledgeConclusionTagLabel)"></h3>
              <a-tag color="green" v-if="item.id!==null&&item.id!==undefined&&item.id
               !==''">
                已同步
              </a-tag>
              <a-tag color="blue" v-else>
                未同步
              </a-tag>
              <a-tag color="purple" >
                <span v-html="toMath(item.knowledgeConclusionLabel)"></span>
              </a-tag>
            </template>
            <template #description>
              <div v-html="toMath(item.techniqueDetail )"></div>
            </template>
            <template #avatar>
              <a-avatar :src="item.avatar" />
            </template>
          </a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
  </a-drawer>
</template>
<style lang="less" scoped>
.buttons{
  box-shadow: 0px 4px 6px -2px rgba(16, 24, 40, 0.03), 0px 12px 16px -4px rgba(16, 24, 40, 0.08);
  background: rgb(255 255 255 / 0.95);
  padding: 5px 20px;
  border-radius: 5px;
}
</style>
